package hu.issue.framework.web.tag;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.TagSupport;

public abstract class FormElementTag extends TagSupport implements DynamicAttributes {

	private static final long serialVersionUID = 101459166419732848L;

	private final Map<String, Object> attributes = new HashMap<String, Object>();
	protected String field;

	public void setField(final String field) {
		this.field = field;
	}

	@Override
	public void setDynamicAttribute(final String uri, final String localName, final Object value) throws JspException {
		this.attributes.put(localName, value);
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			final JspWriter writer = this.pageContext.getOut();
			writer.append("<").append(getTagName()).append(" ");

			writer.append(attribute("name", this.field));
			writer.append(attribute("value", this.pageContext.getRequest().getParameter(this.field)));
			for (final String name : this.attributes.keySet()) {
				final Object value = this.attributes.get(name);
				writer.append(" ").append(attribute(name, value));
			}

			final String tagContent = getTagContent();
			if (tagContent != null) {
				writer.append(">").append(tagContent).append("</").append(getTagName()).append(">");
			} else {
				writer.append("/>");
			}
			return EVAL_PAGE;
		} catch (final IOException ex) {
			throw new JspException(ex);
		}
	}

	protected abstract String getTagName();

	protected String getTagContent() {
		return null;
	}

	private String attribute(final String name, final Object value) {
		if (value == null) {
			return "";
		}

		return String.format("%s=\"%s\"", name, value);
	}

}
